package com.ebt.m.proposal_v2.ui;

import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ebt.m.R;
import com.ebt.m.commons.utils.ActivityUtils;
import com.ebt.m.proposal_v2.adapter.CompatFragmentPagerAdapter;
import com.ebt.m.proposal_v2.bean.temp.ActivityFinishStack;
import com.ebt.m.proposal_v2.dao.request.ParamGetRisks;
import com.ebt.m.proposal_v2.helper.ThemeHelper;
import com.ebt.m.proposal_v2.mvp.base.MVPCompatActivity;
import com.ebt.m.proposal_v2.mvp.contract.MainProductContract;
import com.ebt.m.proposal_v2.mvp.presenter.MainProductPresenter;
import com.ebt.m.proposal_v2.utils.RxUtils;
import com.ebt.m.proposal_v2.widget.common.TopBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 选择主险
 *
 * @author archer.qi
 *         Created on 2017/5/22.
 */
public class MainProductActivity extends MVPCompatActivity<MainProductPresenter> implements MainProductContract.View {

    @BindView(R.id.main_product_topBar)
    TopBar mTopBar;
    @BindView(R.id.main_product_tab_1)
    TextView mTabProduct;
    @BindView(R.id.main_product_tab_2)
    RelativeLayout mTabBrand;
    @BindView(R.id.main_product_tab_2_content)
    TextView mTabBrandText;
    @BindView(R.id.main_product_tab_2_logo)
    ImageView mTabBrandLogo;
    @BindView(R.id.main_product_container)
    FrameLayout mContainer;
    @BindView(R.id.main_product_pager)
    ViewPager mViewPager;
    @BindView(R.id.main_product_indicator_container)
    LinearLayout mIndicatorLayout;
    @BindView(R.id.main_product_indicator)
    View mIndicator;

    public static final String Arg_param = "ArgParam";
    private ParamGetRisks mArg;

    private CommonProductFragment commonProductFragment;
    private BrandSelectFragment brandSelectFragment;

    /* 当前选中*/
    private int mCurrentCheckIndex;
    /* 控制筛选产品开闭*/
    private boolean isBrandOpen = true;
    /* Indicator滚动距离*/
    private float offsetTranslationX;
    /* 缓存滚动动画*/
    private ObjectAnimator mTranslation0To1;
    private ObjectAnimator mTranslation1To0;

    @Override
    public void initArguments() {
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            mArg = (ParamGetRisks) extras.getSerializable(Arg_param);
        }
    }

    @Override
    public void setEmptyView(boolean isEmpty) {
    }

    @Override
    protected MainProductPresenter createPresenter() {
        return new MainProductPresenter(getApplicationContext(), this);
    }

    @Override
    protected int setContentResource() {
        return R.layout.activity_main_products;
    }

    @Override
    protected void onActivityCreate() {
        initArguments();
        initTopBar();
        if (mPresenter.getCompanyType() == MainProductPresenter.COMPANY_TYPE_CRE) {
            initCreditCompanyView();
        } else if (mPresenter.getCompanyType() == MainProductPresenter.COMPANY_TYPE_INS) {
            initInsuranceCompanyView();
        } else {
            initCreditCompanyView();
        }
        initTabSelectListener();
        addToTempStack();
    }

    private void addToTempStack() {
        /**
         * 从选择主险到搜索页面
         * 如果从搜索直接点击产品需要同时finish该页面与搜索页面；这里保存一下该页面
         * 从搜索返回，依旧返回该页面
         * 从搜索选中，同时finish这两个页面
         */
        ActivityFinishStack.getInstance().add(MainProductActivity.this);
    }

    @Override
    protected void onActivityDestroy() {
        if (mTranslation0To1 != null) {
            mTranslation0To1.cancel();
            mTranslation0To1 = null;
        }
        if (mTranslation1To0 != null) {
            mTranslation1To0.cancel();
            mTranslation1To0 = null;
        }
    }

    @Override
    public void initTopBar() {
        mTopBar.showLeft(true);
        mTopBar.showRight(true);
        mTopBar.with(this);
        mTopBar.setTitle("添加主险");
        mTopBar.setRightResource(R.drawable.ic_search);
        mTopBar.setRightClickListener(view -> mPresenter.doSearch(MainProductActivity.this));
    }

    @Override
    public void initCreditCompanyView() {
        toggleTabByStatus(201);
        mViewPager.setVisibility(View.GONE);
        mIndicatorLayout.setVisibility(View.GONE);
        mContainer.setVisibility(View.VISIBLE);
        onTabSelect(0);
        toggleFragment(0);
    }

    @Override
    public void initInsuranceCompanyView() {
        toggleTabByStatus(101);
        mViewPager.setVisibility(View.VISIBLE);
        mIndicatorLayout.setVisibility(View.VISIBLE);
        mContainer.setVisibility(View.GONE);
        initViewPager();
        setDefaultLocation();
    }

    @Override
    public void toggleTabByStatus(int status) {
        if (mPresenter.getCompanyType() == MainProductPresenter.COMPANY_TYPE_INS) {
            if (status == 101) {
            /* 保险公司 - 默认情况*/
                mTabBrandText.setText("全部产品");
                mTabBrandText.setTextColor(ThemeHelper.getColor(this, R.color.PrimaryContentColor));
                mTabBrandLogo.setVisibility(View.GONE);
            }
            if (status == 102) {
            /* 保险公司 - 选中*/
                mTabBrandText.setText("全部产品");
                mTabBrandText.setTextColor(ThemeHelper.getColor(this, R.color.PrimaryThemeColor));
                mTabBrandLogo.setVisibility(View.GONE);
            }
        }
        if (mPresenter.getCompanyType() == MainProductPresenter.COMPANY_TYPE_CRE) {
            if (status == 201) {
            /* 经贷公司 - 默认不选中*/
                if (brandSelectFragment == null) {
                    mTabBrandText.setText("筛选品牌");
                } else {
                    mTabBrandText.setText(brandSelectFragment.getBrandChecked());
                }
                mTabBrandText.setTextColor(ThemeHelper.getColor(this, R.color.PrimaryContentColor));
                mTabBrandLogo.setVisibility(View.VISIBLE);
                mTabBrandLogo.setImageResource(R.drawable.icon_arrow_down_gray);
            }
            if (status == 202) {
            /* 经贷公司 - 选中打开*/
                if (brandSelectFragment == null || "筛选品牌".equals(brandSelectFragment.getBrandChecked())) {
                    mTabBrandText.setText("筛选品牌");
                    mTabBrandText.setTextColor(ThemeHelper.getColor(this, R.color.PrimaryContentColor));
                    mTabBrandLogo.setImageResource(R.drawable.icon_arrow_up_gray);
                } else {
                    mTabBrandText.setText(brandSelectFragment.getBrandChecked());
                    mTabBrandText.setTextColor(ThemeHelper.getColor(this, R.color.PrimaryThemeColor));
                    mTabBrandLogo.setImageResource(R.drawable.ic_proposal_v2_arrow_up_green);
                }
                mTabBrandLogo.setVisibility(View.VISIBLE);
            }
            if (status == 203) {
            /* 经贷公司 - 选中关闭*/
                if (brandSelectFragment == null || "筛选品牌".equals(brandSelectFragment.getBrandChecked())) {
                    mTabBrandText.setText("筛选品牌");
                    mTabBrandText.setTextColor(ThemeHelper.getColor(this, R.color.PrimaryContentColor));
                    mTabBrandLogo.setImageResource(R.drawable.icon_arrow_down_gray);
                } else {
                    mTabBrandText.setText(brandSelectFragment.getBrandChecked());
                    mTabBrandText.setTextColor(ThemeHelper.getColor(this, R.color.PrimaryThemeColor));
                    mTabBrandLogo.setImageResource(R.drawable.ic_proposal_v2_arrow_down_green);
                }
                mTabBrandLogo.setVisibility(View.VISIBLE);

            }
        }
    }

    @Override
    public void initTabSelectListener() {
        RxUtils.click(mTabProduct, view -> {
            if (mCurrentCheckIndex != 0) {
                onTabScroll(0);
                onTabSelect(0);
                toggleFragment(0);
                if (brandSelectFragment != null) { // MenuClose
                    String brandChecked = brandSelectFragment.getBrandChecked();
                    if (TextUtils.isEmpty(brandChecked) || brandChecked.equals("筛选品牌")) {
                        brandSelectFragment.clearBrandChecked();
                    }
                }
            }
        });
        RxUtils.click(mTabBrand, view -> {
            if (mCurrentCheckIndex == 1) {
                /* 经贷公司，点击切换菜单与列表； 保险公司，重复点击无效*/
                if (mPresenter.getCompanyType() == MainProductPresenter.COMPANY_TYPE_CRE) {
                    if (isBrandOpen) {
                        toggleTabByStatus(203); // 关闭，下箭头
                        if (brandSelectFragment != null) { // MenuClose
                            String brandChecked = brandSelectFragment.getBrandChecked();
                            if (TextUtils.isEmpty(brandChecked) || brandChecked.equals("筛选品牌")) {
                                onTabScroll(0);
                                onTabSelect(0);
                                toggleFragment(0);
                                brandSelectFragment.clearBrandChecked();
                            } else {
                                brandSelectFragment.onCloseBrandMenu();
                            }
                        }
                        isBrandOpen = false;
                    } else {
                        toggleTabByStatus(202); // 打开，上箭头
                        if (brandSelectFragment != null) { // MenuOpen
                            brandSelectFragment.onOpenBrandMenu();
                        }
                        isBrandOpen = true;
                    }
                }
            } else {
                isBrandOpen = true;
                onTabScroll(1);
                onTabSelect(1);
                if (brandSelectFragment != null) { // MenuClose
                    brandSelectFragment.clearBrandChecked();
                }
                toggleFragment(1);
            }
        });
    }

    @Override
    public void onTabSelect(int position) {
        if (mPresenter.getCompanyType() == MainProductPresenter.COMPANY_TYPE_CRE) {
            if (position == 0) { // 点击常用产品，默认为选中，重置品牌选项
                mTabProduct.setTextColor(ThemeHelper.getColor(this, R.color.PrimaryThemeColor));
                if (brandSelectFragment != null) {
                    brandSelectFragment.clearBrandChecked();
                }
                toggleTabByStatus(201);
            }
            if (position == 1) {// 点击筛选品牌，默认打开菜单
                toggleTabByStatus(202);
            }
        }
        if (mPresenter.getCompanyType() == MainProductPresenter.COMPANY_TYPE_INS) {
            if (position == 0) {
                mTabProduct.setTextColor(ThemeHelper.getColor(this, R.color.PrimaryThemeColor));
                toggleTabByStatus(101);
            }
            if (position == 1) {
                toggleTabByStatus(102);
                mTabProduct.setTextColor(ThemeHelper.getColor(this, R.color.PrimaryContentColor));
            }
            mViewPager.setCurrentItem(position);
        }

        mCurrentCheckIndex = position;
    }

    @Override
    public void onTabScroll(int position) {
        if (mPresenter.getCompanyType() != MainProductPresenter.COMPANY_TYPE_INS) {
            return;
        }
        if (position == 1) {
            if (mTranslation0To1 == null) {
                mTranslation0To1 = ObjectAnimator.ofFloat(mIndicator, "translationX", 0, offsetTranslationX);
                mTranslation0To1.setDuration(150);
            }
            mTranslation0To1.start();
        }
        if (position == 0) {
            if (mTranslation1To0 == null) {
                mTranslation1To0 = ObjectAnimator.ofFloat(mIndicator, "translationX", offsetTranslationX, 0);
                mTranslation1To0.setDuration(150);
            }
            mTranslation1To0.start();
        }
    }

    @Override
    public void setDefaultLocation() {
        if (offsetTranslationX == 0) {
            int screenWidth = ActivityUtils.getScreenSize(this)[0];
            int indicatorWidth = (int) (ActivityUtils.getScreenDensity(this) * 100);
            int padding = (screenWidth / 2 - indicatorWidth) / 2;
            offsetTranslationX = padding * 2 + indicatorWidth;

            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mIndicator.getLayoutParams();
            layoutParams.leftMargin = padding;
            mIndicator.setLayoutParams(layoutParams);
        }
    }

    @Override
    public void toggleFragment(int position) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (position == 0) {
            if (commonProductFragment == null) {
                commonProductFragment = new CommonProductFragment();
            }
            if (!commonProductFragment.isAdded()) {
                transaction.add(R.id.main_product_container, commonProductFragment);
            }
            if (brandSelectFragment != null && brandSelectFragment.isAdded()) {
                transaction.hide(brandSelectFragment);
            }
            transaction.show(commonProductFragment).commitAllowingStateLoss();
        }
        if (position == 1) {
            if (brandSelectFragment == null) {
                brandSelectFragment = new BrandSelectFragment();
            }
            if (!brandSelectFragment.isAdded()) {
                transaction.add(R.id.main_product_container, brandSelectFragment);
            }
            if (commonProductFragment != null && commonProductFragment.isAdded()) {
                transaction.hide(commonProductFragment);
            }
            transaction.show(brandSelectFragment).commitAllowingStateLoss();
        }
    }

    @Override
    public MainProductPresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public ParamGetRisks getArgument() {
        return mArg;
    }

    @Override
    public void initViewPager() {
        if (commonProductFragment == null) {
            commonProductFragment = new CommonProductFragment();
        }
        if (brandSelectFragment == null) {
            brandSelectFragment = new BrandSelectFragment();
        }
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(commonProductFragment);
        fragments.add(brandSelectFragment);
        mViewPager.setAdapter(new CompatFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                onTabScroll(position);
                onTabSelect(position);
                toggleFragment(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        mViewPager.setCurrentItem(0);
    }

    @Override
    public void updateBrandText(String text) {
        mTabProduct.setTextColor(ThemeHelper.getColor(this, R.color.PrimaryContentColor));
        mTabBrandText.setText(text);
        isBrandOpen = false;
        toggleTabByStatus(203);
    }

}
